package cn.tedu.mall.order.listener;

import cn.tedu.mall.front.service.IFrontSkuService;
import cn.tedu.mall.order.mapper.OrderItemMapper;
import cn.tedu.mall.order.mapper.OrderMapper;
import cn.tedu.mall.pojo.order.dto.OrderAddCondition;
import cn.tedu.mall.pojo.order.model.OmsOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RocketMQTransactionListener
public class TransactionOrderAddListener implements RocketMQLocalTransactionListener {
    /**
     * 执行本地事务,减库存,生订单,发延迟消息
     *
     * @param msg
     * @param arg
     * @return
     */
    @DubboReference
    private IFrontSkuService skuService;

    @Autowired//操作表格 oms_order
    private OrderMapper orderMapper;

    @Autowired//操作表格oms_order_item
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderAddListenerRegister register;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        OrderAddCondition orderAddCondition = (OrderAddCondition) arg;
        return register.execute(orderAddCondition);
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String orderClass = (String) msg.getHeaders().get("name");
        if (orderClass != null && orderClass.equals("localAdd")) {
            //TODO
        } else if (orderClass != null && orderClass.equals("seckillAdd")) {
            //TODO
        }
        //检查订单 sn 从消息中解析sn
        String sn = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        //查询到订单 return commit
        OmsOrder order = orderMapper.selectOrderBySn(sn);
        if (order != null) {
            //不能commit 检查是否存在orderItems
            Integer count = orderItemMapper.selectCountByOrderId(order.getId());
            if (count != 0) {
                return RocketMQLocalTransactionState.COMMIT;
            } else {
                //TODO 可以选择在有订单,但是没有订单商品的时候,将订单删除
                log.debug("有订单,但是没订单商品,记录日志");
            }
        }
        //没查到 回退库存
        skuService.returnStock(sn);
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
